package com.jwong.grpc.loadbalancer;

import io.grpc.Attributes;
import io.grpc.EquivalentAddressGroup;
import io.grpc.NameResolver;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DirectMultiAddressNameResolver extends NameResolver {

    private final String target;

    public DirectMultiAddressNameResolver(String target) {
        this.target = target;
    }


    @Override
    public String getServiceAuthority() {
        return "localhost";
    }

    @Override
    public void start(Listener listener) {
        String[] targetArray = target.split(",");
        List<EquivalentAddressGroup> addressGroups = new ArrayList<>();
        Arrays.stream(targetArray).forEach(t -> {
            String[] address = t.split(":");
            EquivalentAddressGroup equivalentAddressGroup = new EquivalentAddressGroup(
                    new InetSocketAddress(address[0], Integer.parseInt(address[1])));
            addressGroups.add(equivalentAddressGroup);

        });
        listener.onAddresses(addressGroups, Attributes.EMPTY);
    }

    @Override
    public void refresh() {
        System.out.println("target = " + target);
    }

    @Override
    public void shutdown() {
    }

}
